<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>观察者模式(发布订阅)</title>
</head>
<body>
  
  <script>
    //  观察者模式指的是函数自动观察数据对象的模式，一旦对象的数据发生了变化，函数就会自动执行
    // js中可以借助proxy来实现观察者模式
    // 数据被称为观察目标，而执行触发执行的函数则是观察者

    const queuedObservers = new Set()

    const observe = fun => queuedObservers.add(fun)

    const observable = obj => new Proxy(obj, {set})

    function set (target, key, value, receiver) {
      const result = Reflect.set(target, key, value, receiver)
      queuedObservers.forEach(observer => observer())
      return result
    }

    const person = observable({
      name: '张三',
      age: 20
    })
    function print () {
      console.log(`${person.name}, ${person.age}`)
    }
    observe(print)

    person.name = 'Jacob'
  </script>
</body>
</html>